package com.common.web;

import java.text.SimpleDateFormat;
import java.util.Date;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import com.core.privilege.CheckPrivilegeResultEnum;
import com.core.privilege.bo.PrivilegeBo;
import com.core.sysLog.bo.SysLogBo;
import com.core.sysLog.pojo.SysLog;
import com.core.user.pojo.User;
import com.interfaces.SysLoginController;


public class CommonInterceptor extends HandlerInterceptorAdapter {
	protected Logger	log	= Logger.getLogger(this.getClass());

	@Autowired
	private PrivilegeBo	privilegeBo;
	@Autowired
	private SysLogBo sysLogBo;
	private SysLog sysLog;
	/*
	 * 利用正则映射到需要拦截的路径
	 * 
	 * private String mappingURL;
	 * 
	 * public void setMappingURL(String mappingURL) { this.mappingURL = mappingURL; }
	 */

	/**
	 * 在业务处理器处理请求之前被调用 如果返回false 从当前的拦截器往回执行所有拦截器的afterCompletion(),再退出拦截器链
	 * <p>
	 * 如果返回true 执行下一个拦截器,直到所有的拦截器都执行完毕 再执行被拦截的Controller 然后进入拦截器链, 从最后一个拦截器往回执行所有的postHandle() 接着再从最后一个拦截器往回执行所有的afterCompletion()
	 */
	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
		String requestUri = request.getRequestURI();
		String contextPath = request.getContextPath();
		request.getAttribute("distributor_code");
		if ("/".equals(contextPath)) {
			contextPath = "";
		}
		String url = requestUri.substring(contextPath.length());

		log.info("requestUri:" + requestUri);
		log.info("contextPath:" + contextPath);
		log.info("url:" + url);

		User userInfo = (User) request.getSession().getAttribute(CommonKeys.SESSION_USER);

		boolean rtn = true;
		//
		CheckPrivilegeResultEnum result = privilegeBo.checkPrivilege(userInfo, url);
		switch (result) {
		case RETURN_TRUE:
			rtn = true;
			break;
		case NEED_LOGIN:
			response.sendRedirect(contextPath + SysLoginController.URL_GOTO_LOGIN_PAGE);
			// request.getRequestDispatcher(SysLoginController.URL_GOTO_LOGIN_PAGE).forward(request, response);
			rtn = false;
			break;
		case NO_AUTHORITY:
			response.sendRedirect(contextPath + "/error/no_access.html");
			// request.getRequestDispatcher("/error/no_access.html").forward(request, response);
			rtn = false;
			break;
		}

		return rtn;
	}
	public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception{
		try {
			//记录操作日志
			sysLog = new SysLog();
			//用户信息
			User userInfo = (User) request.getSession().getAttribute(CommonKeys.SESSION_USER);
			if(userInfo==null) return;
			sysLog.setUser_id(userInfo.getId());
			//请求URL-功能
			String requestUri = request.getRequestURI();
			String contextPath = request.getContextPath();
			if ("/".equals(contextPath)) {
				contextPath = "";
			}
			String url = requestUri.substring(contextPath.length());
			sysLog.setUrl(url);
			SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
			String dateString = formatter.format(new Date());
			sysLog.setAdd_time(dateString);
			if(ex==null){
				sysLog.setIssuccess(1);
			}else{
				sysLog.setIssuccess(0);
			}
			sysLogBo.add(sysLog);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			//e.printStackTrace();
			log.error("记录操作日志error：", e);
		}
	}
}
